<?php


namespace app\community\oauth2\Repository;


use app\community\oauth2\Entities\AccessTokenEntity;
use app\community\oauth2\Model\oauthClientAccessTokenModel;
use iflow\Response;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;

class AccessTokenRepository implements AccessTokenRepositoryInterface
{
    /**
     * AccessToken 实体 返回响应时会调用该方法返回类
     * @param ClientEntityInterface $clientEntity
     * @param array $scopes
     * @param null $userIdentifier
     * @return mixed
     */
    public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null): mixed
    {
        // TODO: Implement getNewToken() method.
        return app(AccessTokenEntity::class)
                -> setUserIdentifier($userIdentifier)
                -> setClient($clientEntity);
    }

    /**
     * 创建完新的 TOKEN后将会回调该方法 可写入数据库
     * @param AccessTokenEntityInterface $accessTokenEntity
     * @return Response
     * @throws \app\community\oauth2\Exception\ClientException
     */
    public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity): Response
    {
        // TODO: Implement persistNewAccessToken() method.
        return (new oauthClientAccessTokenModel()) -> saveAccessToken($accessTokenEntity);
    }

    /**
     * 撤销令牌
     * @param string $tokenId
     * @return Response
     */
    public function revokeAccessToken($tokenId): Response
    {
        // TODO: Implement revokeAccessToken() method.
        return (new oauthClientAccessTokenModel()) -> revokeAccessToken($tokenId);
    }

    /**
     * 验证TOKEN是否过期
     * @param string $tokenId
     * @return bool
     * @throws \app\community\oauth2\Exception\ClientNotFoundException
     */
    public function isAccessTokenRevoked($tokenId): bool
    {
        // TODO: Implement isAccessTokenRevoked() method.
        return (new oauthClientAccessTokenModel()) -> validateAccessToken($tokenId);
    }
}